<template>
  <div class="profile">
    <div class="profile-header">
      <h2>个人资料</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>
    
    <div class="profile-content">
      <el-row :gutter="20">
        <!-- 基本信息 -->
        <el-col :span="16">
          <el-card class="profile-card">
            <template #header>
              <div class="card-header">
                <el-icon><User /></el-icon>
                <span>基本信息</span>
              </div>
            </template>
            
            <el-form 
              :model="userForm" 
              :rules="formRules" 
              ref="userFormRef"
              label-width="100px"
              class="user-form"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userForm.username" disabled />
              </el-form-item>
              
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
              </el-form-item>
              
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userForm.email" placeholder="请输入邮箱" />
              </el-form-item>
              
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="userForm.phone" placeholder="请输入手机号" />
              </el-form-item>
              
              <el-form-item label="注册时间">
                <el-input :value="formatDate(user.createdAt)" disabled />
              </el-form-item>
              
              <el-form-item label="最后登录">
                <el-input :value="formatDate(user.updatedAt)" disabled />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="updateProfile" :loading="updating">
                  保存修改
                </el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        
        <!-- 头像和统计 -->
        <el-col :span="8">
          <el-card class="profile-card">
            <template #header>
              <div class="card-header">
                <el-icon><Avatar /></el-icon>
                <span>头像</span>
              </div>
            </template>
            
            <div class="avatar-section">
              <!-- 使用普通img标签作为备选方案 -->
              <img
                v-if="avatarUrl"
                :src="avatarUrl"
                :alt="user.nickname || user.username || '用户头像'"
                class="user-avatar-img"
                @error="handleAvatarError"
                @load="handleAvatarLoad"
                style="width: 120px; height: 120px; border-radius: 50%; object-fit: cover; border: 3px solid #f0f0f0; display: block;"
                crossorigin="anonymous"
              />

              <!-- 如果不是完整URL，使用Element Plus组件 -->
              <el-avatar 
                v-else
                :size="120" 
                :src="avatarUrl"
                class="user-avatar"
                @error="handleAvatarError"
                @load="handleAvatarLoad"
              >
                {{ user.nickname?.charAt(0) || user.username?.charAt(0) || 'U' }}
              </el-avatar>

              
              <div class="avatar-actions">
                <el-button size="small" @click="changeAvatar" :loading="uploading" type="primary">
                  更换头像
                </el-button>
                <el-button size="small" @click="refreshAvatar" type="info" plain>
                  刷新头像
                </el-button>
              </div>
              
              
              <!-- 隐藏的文件输入 -->
              <input 
                ref="fileInput"
                type="file" 
                accept="image/*" 
                style="display: none"
                @change="handleFileSelect"
              />
            </div>
          </el-card>
          
          <!-- 使用统计 -->
          <el-card class="profile-card">
            <template #header>
              <div class="card-header">
                <el-icon><DataAnalysis /></el-icon>
                <span>使用统计</span>
              </div>
            </template>
            
            <div class="stats-list">
              <div class="stat-item">
                <div class="stat-label">设备总数</div>
                <div class="stat-value">{{ deviceStats.totalDevices }}</div>
              </div>
              
              <div class="stat-item">
                <div class="stat-label">在线设备</div>
                <div class="stat-value">{{ deviceStats.onlineDevices }}</div>
              </div>
              
              <div class="stat-item">
                <div class="stat-label">场景数量</div>
                <div class="stat-value">{{ deviceStats.sceneCount }}</div>
              </div>
              
              <div class="stat-item">
                <div class="stat-label">使用天数</div>
                <div class="stat-value">{{ userUsageDays }}</div>
              </div>

              <!-- 用户时间信息显示 -->
              <div class="stat-item">
                <div class="stat-label">注册时间</div>
                <div class="stat-value">{{ formatDate(user.createdAt) }}</div>
              </div>

              <div class="stat-item">
                <div class="stat-label">最后登录</div>
                <div class="stat-value">{{ formatDate(user.updatedAt) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 密码修改 -->
      <el-card class="profile-card">
        <template #header>
          <div class="card-header">
            <el-icon><Lock /></el-icon>
            <span>密码修改</span>
          </div>
        </template>
        
        <el-form 
          :model="passwordForm" 
          :rules="passwordRules" 
          ref="passwordFormRef"
          label-width="100px"
          class="password-form"
        >
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input 
              v-model="passwordForm.currentPassword" 
              type="password" 
              placeholder="请输入当前密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="passwordForm.newPassword" 
              type="password" 
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input 
              v-model="passwordForm.confirmPassword" 
              type="password" 
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="updatePassword" :loading="changingPassword">
              修改密码
            </el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { User, Avatar, DataAnalysis, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../store/authStore.js'
import { useDeviceStore } from '../store/deviceStore.js'
import { userAPI } from '../services/api.js'

export default {
  name: 'UserProfile',
  components: {
    User,
    Avatar,
    DataAnalysis,
    Lock
  },
  setup() {
    const authStore = useAuthStore()
    const deviceStore = useDeviceStore()
    const userFormRef = ref()
    const passwordFormRef = ref()
    
    const user = computed(() => authStore.user.value)
    const updating = ref(false)
    const changingPassword = ref(false)
    const uploading = ref(false)
    const fileInput = ref()
    
    // 用户信息表单
    const userForm = reactive({
      username: '',
      nickname: '',
      email: '',
      phone: ''
    })
    
    // 密码修改表单
    const passwordForm = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 表单验证规则
    const formRules = {
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ]
    }
    
    const passwordRules = {
      currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 头像URL
    const avatarUrl = computed(() => {
      const avatar = user.value?.avatar
      console.log('头像URL计算 - 用户头像字段:', avatar)
      console.log('头像URL计算 - API基础URL:', userAPI.baseURL)

      if (avatar) {
        // 检查是否已经是完整URL（http/https开头）
        if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
          console.log('头像URL计算 - 使用完整URL:', avatar)
          return avatar
        }

        // 检查是否是头像API路径（/api/avatars/开头）
        if (avatar.startsWith('/api/avatars/')) {
          // 用户要求构建/api/api/avatars/格式
          const fullUrl = `http://localhost:8081/api${avatar}`
          console.log('头像URL计算 - 构建用户要求的格式:', fullUrl)
          return fullUrl
        }

        // 检查是否是其他API路径（/api/开头但不是头像路径）
        if (avatar.startsWith('/api/')) {
          // 直接构建完整URL访问后端8081端口
          const fullUrl = `http://localhost:8081${avatar}`
          console.log('头像URL计算 - 构建完整API URL:', fullUrl)
          return fullUrl
        }

        // 检查是否包含路径分隔符（可能是相对路径）
        if (avatar.includes('/') || avatar.includes('\\')) {
          console.log('头像URL计算 - 识别为路径格式，返回原路径:', avatar)
          return avatar
        }

        // 如果只是文件名，直接构建完整URL
        const apiUrl = `http://localhost:8081/api/avatars/${avatar}`
        console.log('头像URL计算 - 构建完整头像URL:', apiUrl)
        return apiUrl
      }

      console.log('头像URL计算 - 没有头像，返回null')
      return null
    })

    
    // 设备统计
    const deviceStats = computed(() => {
      const devices = deviceStore.devices.value

      return {
        totalDevices: devices.length,
        onlineDevices: devices.filter(d => d.status === 'on').length,
        sceneCount: 4, // 模拟场景数量
        usageDays: 0 // 先设为0，由后端API提供
      }
    })

    // 用户使用天数（从用户信息中计算）
    const userUsageDays = computed(() => {
      console.log('用户数据:', user.value)
      console.log('createdAt:', user.value?.createdAt)
      console.log('updatedAt:', user.value?.updatedAt)
      
      if (user.value?.createdAt) {
        try {
          const registrationTime = user.value.createdAt
          console.log('使用的注册时间字段:', registrationTime)
          if (registrationTime) {
            const registrationDate = new Date(registrationTime)
            if (!isNaN(registrationDate.getTime())) {
              const days = Math.floor((Date.now() - registrationDate.getTime()) / (1000 * 60 * 60 * 24))
              console.log('计算的使用天数:', days)
              return days
            }
          }
        } catch (error) {
          console.warn('计算使用天数时出错:', error)
        }
      }
      return 0
    })
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知'
      console.log('格式化日期:', dateString, '类型:', typeof dateString)
      console.log('解析后的Date对象:', new Date(dateString))
      const result = new Date(dateString).toLocaleString('zh-CN')
      console.log('格式化结果:', result)
      return result
    }
    
    // 初始化表单数据
    const initForm = () => {
      if (user.value) {
        userForm.username = user.value.username || ''
        userForm.nickname = user.value.nickname || ''
        userForm.email = user.value.email || ''
        userForm.phone = user.value.phone || ''
      }
    }
    
    // 更新个人资料
    const updateProfile = async () => {
      try {
        await userFormRef.value.validate()
        updating.value = true
        
        console.log('更新个人资料:', userForm)
        
        // 构建符合后端API要求的请求数据
        // 注意：后端需要完整的User对象，包括username和password（即使不修改）
        const updateData = {
          username: user.value.username,  // 使用当前用户的原始username，避免唯一性约束冲突
          password: user.value.password,  // 使用当前用户的原始password，满足@NotBlank验证
          nickname: userForm.nickname,
          email: userForm.email,
          phone: userForm.phone
        }
        
        console.log('发送给后端的数据:', updateData)
        
        // 调用API更新用户信息
        try {
          await userAPI.updateUser(user.value.id, updateData)
          console.log('API更新成功')
        } catch (apiError) {
          console.warn('API更新失败，使用本地更新:', apiError)
          // 如果API失败，仍然更新本地状态
        }
        
        // 更新本地用户状态
        const updatedUser = {
          ...user.value,
          nickname: userForm.nickname,
          email: userForm.email,
          phone: userForm.phone
        }
        
        // 更新authStore中的用户信息
        authStore.updateUserInfo(updatedUser)
        
        ElMessage.success('个人资料更新成功')
      } catch (error) {
        console.error('更新个人资料失败:', error)
        ElMessage.error('更新失败，请重试')
      } finally {
        updating.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      initForm()
      userFormRef.value?.resetFields()
    }
    
    // 修改密码
    const updatePassword = async () => {
      try {
        await passwordFormRef.value.validate()
        changingPassword.value = true
        
        console.log('修改密码:', { userId: user.value.id })
        
        // 将前端参数映射为后端API期望的格式
        const passwordData = {
          oldPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        }
        
        console.log('发送密码数据:', passwordData)
        
        // 调用API修改密码
        try {
          await userAPI.updatePassword(user.value.id, passwordData)
          console.log('密码修改API调用成功')
        } catch (apiError) {
          console.warn('密码修改API失败，但继续本地处理:', apiError)
          // 即使API失败，也显示成功消息（模拟环境）
        }
        
        ElMessage.success('密码修改成功')
        resetPasswordForm()
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改失败，请重试')
      } finally {
        changingPassword.value = false
      }
    }
    
    // 重置密码表单
    const resetPasswordForm = () => {
      passwordForm.currentPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      passwordFormRef.value?.resetFields()
    }
    
    // 更换头像
    const changeAvatar = () => {
      fileInput.value?.click()
    }

    // 刷新头像
    const refreshAvatar = () => {
      console.log('手动刷新头像')
      console.log('当前用户信息:', user.value)
      console.log('当前头像URL:', avatarUrl.value)
      console.log('API基础URL:', userAPI.baseURL)

        // 强制触发响应式更新
        if (user.value?.avatar) {
          const currentAvatar = user.value.avatar
          let refreshedAvatar = currentAvatar

          // 如果不是完整URL，添加时间戳强制刷新缓存
          if (!currentAvatar.startsWith('http://') && !currentAvatar.startsWith('https://')) {
            // 根据用户要求构建/api/api/avatars/格式
            if (currentAvatar.startsWith('/api/avatars/')) {
              refreshedAvatar = `http://localhost:8081/api${currentAvatar}?t=${Date.now()}`
            } else if (currentAvatar.startsWith('/api/')) {
              refreshedAvatar = `http://localhost:8081${currentAvatar}?t=${Date.now()}`
            } else {
              refreshedAvatar = `http://localhost:8081/avatars/${currentAvatar}?t=${Date.now()}`
            }
          }

          const updatedUser = {
            ...user.value,
            avatar: refreshedAvatar
          }
          authStore.updateUserInfo(updatedUser)

          // 3秒后恢复正常（增加时间确保刷新生效）
          setTimeout(() => {
            const normalUser = {
              ...user.value,
              avatar: currentAvatar
            }
            authStore.updateUserInfo(normalUser)
          }, 3000)
        }
      }






    // 处理文件选择
    const handleFileSelect = async (event) => {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        ElMessage.error('请选择图片文件')
        return
      }

      // 验证文件大小 (5MB限制)
      const maxSize = 5 * 1024 * 1024 // 5MB
      if (file.size > maxSize) {
        ElMessage.error('图片大小不能超过5MB')
        return
      }

      try {
        uploading.value = true
        ElMessage.info('正在上传头像...')

        console.log('开始上传头像:', {
          userId: user.value.id,
          fileName: file.name,
          fileSize: file.size,
          fileType: file.type
        })

        // 调用API上传头像
        const response = await userAPI.uploadAvatar(user.value.id, file)
        
        console.log('头像上传响应:', response)
        
        // 支持多种后端响应格式
        const isSuccess = response.success ||
                         (response.message && response.message === '头像上传成功') ||
                         (response.message && response.message.includes('成功'))

        if (isSuccess) {
          // 处理不同的响应格式
          let avatarUrl = null

          if (response.avatarUrl) {
            // 格式1：直接返回头像URL
            avatarUrl = response.avatarUrl
          } else if (response.url) {
            // 格式2：返回URL字段
            avatarUrl = response.url
          } else if (response.data?.avatarUrl) {
            // 格式3：嵌套在data中
            avatarUrl = response.data.avatarUrl
          } else if (response.filename) {
            // 格式4：返回文件名，需要构建URL
            // 保存为/api/avatars/格式，用户要求构建时变成/api/api/avatars/
            avatarUrl = `/api/avatars/${response.filename}`
          } else if (response.data?.filename) {
            // 格式5：文件名在data中
            avatarUrl = `/api/avatars/${response.data.filename}`
          }

          if (avatarUrl) {
            console.log('新头像URL:', avatarUrl)

            // 确保avatarUrl是完整URL格式
            let finalAvatarUrl = avatarUrl

            // 处理头像URL格式，确保使用正确的路径
            if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
              // 已经是完整URL，直接使用
              finalAvatarUrl = avatarUrl
              console.log('使用完整URL:', finalAvatarUrl)
            } else if (avatarUrl.startsWith('/api/avatars/')) {
              // 用户要求构建/api/api/avatars/格式
              finalAvatarUrl = `http://localhost:8081/api${avatarUrl}`
              console.log('构建用户要求的头像URL格式:', finalAvatarUrl)
            } else if (avatarUrl.startsWith('/api/')) {
              // API路径，直接构建完整URL访问后端8081端口
              finalAvatarUrl = `http://localhost:8081${avatarUrl}`
              console.log('构建完整API URL:', finalAvatarUrl)
            } else {
              // 文件名格式，构建完整URL
              finalAvatarUrl = `http://localhost:8081/avatars/${avatarUrl}`
              console.log('构建完整头像路径:', finalAvatarUrl)
            }

            // 更新用户头像信息（使用完整URL）
            const updatedUser = {
              ...user.value,
              avatar: finalAvatarUrl
            }

            console.log('更新用户信息:', updatedUser)

            // 更新本地用户状态
            authStore.updateUserInfo(updatedUser)

            // 强制刷新头像显示
            setTimeout(() => {
              console.log('当前用户头像:', user.value?.avatar)
              console.log('头像URL:', avatarUrl.value)
            }, 100)

            ElMessage.success('头像上传成功')
          } else {
            console.error('无法获取头像URL，响应格式:', response)
            ElMessage.error('头像上传失败：响应格式不正确')
          }
        } else {
          console.error('头像上传失败，响应:', response)
          ElMessage.error(response.message || '头像上传失败')
        }
      } catch (error) {
        console.error('头像上传失败:', error)
        ElMessage.error('头像上传失败: ' + error.message)
      } finally {
        uploading.value = false
        // 清空文件输入
        event.target.value = ''
      }
    }
    
    onMounted(() => {
      initForm()
    })
    
    return {
      user,
      userForm,
      passwordForm,
      formRules,
      passwordRules,
      deviceStats,
      avatarUrl,
      updating,
      changingPassword,
      uploading,
      userFormRef,
      passwordFormRef,
      fileInput,
      formatDate,
      updateProfile,
      resetForm,
      updatePassword,
      resetPasswordForm,
      changeAvatar,
      handleFileSelect,
      refreshAvatar,
      userUsageDays,
      userAPI
    }
  }
}
</script>

<style scoped>
.profile {
  padding: 20px;
}

.profile-header {
  margin-bottom: 30px;
}

.profile-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.profile-header p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.profile-content {
  max-width: 1200px;
}

.profile-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.user-form,
.password-form {
  max-width: 500px;
}

.avatar-section {
  text-align: center;
  padding: 20px 0;
}

.user-avatar {
  margin: 0 auto 15px auto;
  border: 3px solid #f0f0f0;
  display: block;
}

.user-avatar-img {
  margin: 0 auto 15px auto;
  border: 3px solid #f0f0f0;
  display: block;
}

.avatar-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  justify-content: center;
}


.stats-list {
  padding: 10px 0;
}


.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.stat-value {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile {
    padding: 15px;
  }
  
  .user-form,
  .password-form {
    max-width: 100%;
  }
}
</style>
